package com.wujie.hello.spring.cloud.alibaba.nacos.oauth.authorization.service;

import com.wujie.hello.spring.cloud.alibaba.nacos.oauth.authorization.dao.TAuthoritiesMapper;
import com.wujie.hello.spring.cloud.alibaba.nacos.oauth.authorization.dao.TSideMenuAuthorityMapper;
import com.wujie.hello.spring.cloud.alibaba.nacos.oauth.authorization.dao.TUsersMapper;
import com.wujie.hello.spring.cloud.alibaba.nacos.oauth.authorization.dto.UserDetailsDto;
import com.wujie.hello.spring.cloud.alibaba.nacos.oauth.authorization.pojo.TAuthorities;
import com.wujie.hello.spring.cloud.alibaba.nacos.oauth.authorization.pojo.TUsers;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wujie
 * @version 1.0.0:
 * @title UserDetailsServiceImpl
 * @Description TODO
 * @dateTime 2020/9/9 10:05
 * @Copyright 2020-2021
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private TUsersMapper tUsersMapper;
    @Resource
    private TAuthoritiesMapper tAuthoritiesMapper;
    @Resource
    private TSideMenuAuthorityMapper tSideMenuAuthorityMapper;
    /**
     * 密码模式查询用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TUsers user = new TUsers();
        user.setUsername(s);
        TUsers select = tUsersMapper.selectOne(user);
        UserDetailsDto userDetailsDto = new UserDetailsDto();
        userDetailsDto.setEnable(true);
        userDetailsDto.setAccountNonExpired(true);
        userDetailsDto.setAccountNonLocked(true);
        userDetailsDto.setCredentialsNonExpired(true);
        //这里权限列表,这个为方便直接下（实际开发中查询用户时连表查询出权限）
        TAuthorities tAuthorities = new TAuthorities();
        tAuthorities.setUserId(select.getId());
        List<TAuthorities> select1 = tAuthoritiesMapper.select(tAuthorities);
        String authorities = select1.stream().map(TAuthorities::getAuthority).map(String::valueOf).collect(Collectors.joining(","));
        BeanUtils.copyProperties(select,userDetailsDto);
        userDetailsDto.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(authorities));
        return userDetailsDto;
    }
}
